﻿/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Probel.Ldoc.Views.ToolBoxes
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Xml;

    using ICSharpCode.AvalonEdit.CodeCompletion;
    using ICSharpCode.AvalonEdit.Highlighting;
    using ICSharpCode.AvalonEdit.Highlighting.Xshd;

    using Probel.Ldoc.Services.Helpers;
    using Probel.Ldoc.ViewModels.ToolBoxes;
    using Probel.Ldoc.Views.Helpers.Avalon;

    /// <summary>
    /// Interaction logic for MacroEditorView.xaml
    /// </summary>
    public partial class MacroEditorView : Window
    {
        #region Constructors

        public MacroEditorView(MacroEditorViewModel viewmodel)
        {
            this.InitialiseAvalonEdit();
            this.InitializeComponent();
            this.InitialiseAvalonBehaviour();

            this.DataContext = viewmodel;
        }

        #endregion Constructors

        #region Properties

        private CompletionWindow CompletionWindow
        {
            get;
            set;
        }

        private MacroEditorViewModel ViewModel
        {
            get { return this.DataContext as MacroEditorViewModel; }
        }

        #endregion Properties

        #region Methods

        private void editor_TextChanged(object sender, EventArgs e)
        {
            //For whatever reason, the first time this event is triggered, the resultView is null
            if (this.resultView != null)
            {
                this.resultView.Text = this.ViewModel.Resolve(this.editor.Text);

                if (this.ViewModel.CurrentMacro != null) { this.ViewModel.CurrentMacro.Expression = this.editor.Text; }
            }
        }

        private void InitialiseAvalonBehaviour()
        {
            editor.TextArea.TextEntering += (sender, e) =>
            {
                if (e.Text.Length > 0 && CompletionWindow != null)
                {
                    if (!char.IsLetterOrDigit(e.Text[0]))
                    {
                        // Whenever a non-letter is typed while the completion window is open,
                        // insert the currently selected element.
                        CompletionWindow.CompletionList.RequestInsertion(e);
                    }
                }
                // do not set e.Handled=true - we still want to insert the character that was typed
            };
            editor.TextArea.TextEntered += (sender, e) =>
            {
                if (e.Text == Markups.GetOpenMarkup())
                {
                    // open code completion after the user has pressed dot:
                    CompletionWindow = new CompletionWindow(editor.TextArea);

                    // provide AvalonEdit with the data:
                    IList<ICompletionData> data = CompletionWindow.CompletionList.CompletionData;
                    foreach (var keyword in CompletionData.GetCompletion()) { data.Add(keyword); }
                    CompletionWindow.Show();
                    CompletionWindow.Closed += delegate
                    {
                        CompletionWindow = null;
                    };
                }
            };
        }

        private void InitialiseAvalonEdit()
        {
            // Load our custom highlighting definition
            IHighlightingDefinition customHighlighting;
            using (Stream stream = typeof(MacroEditorView).Assembly.GetManifestResourceStream("Probel.Ldoc.Views.Helpers.Avalon.MacroHighlighting.xshd"))
            {
                if (stream == null) { throw new InvalidOperationException("Could not Get embedded resource"); }

                using (XmlReader reader = new XmlTextReader(stream))
                {
                    customHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }
            // and register it in the HighlightingManager
            HighlightingManager.Instance.RegisterHighlighting("Macro Highlighting", new string[] { ".cool" }, customHighlighting);
        }

        #endregion Methods
    }
}